<template>
  <div class="app-container">
    <div class="app-content-container">
      <grid-table
        ref="gridTable"
        border="inner"
        name="DatasourceManager"
        :loading.sync="loading"
        :query="queryParams"
        show-overflow
        :buttons.sync="buttons"
        :perfect="true"
        :show-search="true"
        :columns="tableColumns"
        :table-data="datasourceList"
        @current-change="handleCurrentChange"
        @cell-dblclick="handleEdit"
        @remote-method="getList">
        <template v-slot:search-form>
          <el-form :model="queryParams" size="mini" ref="queryForm" :inline="true" class="inline-form" v-show="showSearch">
            <el-form-item label="连接名" prop="datasource">
              <el-input
                v-model="queryParams.datasource"
                placeholder="请输入连接名称"
                clearable
                @keyup.enter.native="handleQuery"/>
            </el-form-item>
          </el-form>
        </template>
      </grid-table>
    </div>
    <!-- 添加或修改数据源对话框 -->
    <vxe-modal
      v-model="open"
      :z-index="100"
      :esc-closable="true"
      transfer
      show-footer
      lock-view
      lock-scroll
      :position="{ top: 100, left: 'center' }"
      :title="title"
      destroy-on-close
      width="650px"
      height="550px"
      resize>
      <template v-slot>
        <el-form ref="form" size="mini" :model="form" :rules="rules" label-width="110px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="数据库类型" prop="databaseType">
                <el-select v-model="form.databaseType" placeholder="请选择数据库类型" @change="selectDatabaseType">
                  <el-option
                    v-for="dict in databaseTypes"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据源" prop="datasource">
                <el-input v-model="form.datasource"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户名" prop="jdbcUserName">
                <el-input v-model="form.jdbcUserName"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="jdbcPassword">
                <el-input v-model="form.jdbcPassword" type="password"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="主机名或ip地址" prop="host">
                <el-input v-model="form.host"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="端口" prop="port">
                <el-input v-model="form.port"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item :label="form.databaseType === 'oracle' ? '服务名' : '数据库'" prop="databaseName">
                <el-input v-model="form.databaseName"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="JDBC URL" prop="jdbcUrl">
                <el-input
                  v-model="form.jdbcUrl"
                  :autosize="{ minRows: 3, maxRows: 6}"
                  type="textarea"
                  placeholder="jdbc url"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="JDBC驱动类" prop="jdbcDriverClass">
                <el-input v-model="form.jdbcDriverClass" placeholder="jdbc驱动类" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="注释" prop="comments">
                <el-input
                  v-model="form.comments"
                  :autosize="{ minRows: 2, maxRows: 4}"
                  type="textarea"
                  placeholder="请输入注释"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-button type="text" style="float: right" @click="() => { testConnect({ row: currentRow }); }">测试连接</el-button>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template v-slot:footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import GridTable from '@/components/GridTable'
  import { listDatasource, addDatasource, updateDatasource, deleteDatasource, testDatasource } from "@/api/datax/datasource";
  import { parseStrEmpty } from "@/utils/common";
  import crypto from "@/utils/crypto";

  export default {
    name: "Datasource",
    components: { GridTable },
    data() {
      return {
        title: undefined,
        databaseTypes: [
          { value: 'mysql', label: 'mysql' },
          { value: 'oracle', label: 'oracle' },
          { value: 'postgresql', label: 'postgresql' },
          { value: 'sqlserver', label: 'sqlserver' }
        ],
        // 数据源状态字典
        databaseTypeOptions: [],
        form: {
          id: undefined,
          datasource: undefined,
          databaseType: undefined,
          databaseName: undefined,
          host: undefined,
          port: undefined,
          jdbcUserName: undefined,
          jdbcPassword: undefined,
          jdbcUrl: undefined,
          jdbcDriverClass: undefined,
          status: 0,
          comments: undefined,
        },
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          datasource: undefined,
        },
        open: false,
        datasourceList: [],
        tableColumns: [
          { field: 'id', title: 'ID', width: 80, headerAlign: 'center', align: 'center' },
          { field: 'databaseType', title: '数据库类型', width: 120, headerAlign: 'center', align: 'center' },
          { field: 'datasource', title: '数据源', width: 120, headerAlign: 'center', align: 'center' },
          { field: 'databaseName', title: '数据库', width: 120, headerAlign: 'center', align: 'center' },
          { field: 'jdbcUrl', title: 'JDBC URL', width: "auto", headerAlign: 'center', align: 'center' },
          { field: 'jdbcDriverClass', title: 'JDBC驱动类', width: "auto", headerAlign: 'center', align: 'center' },
          { field: 'createTime', title: '创建日期', width: 140, headerAlign: 'center', align: 'center' },
          { field: 'createBy', title: '创建人', width: 100, headerAlign: 'center', align: 'center' },
          { field: 'status', title: '状态', width: 100, headerAlign: 'center', align: 'center',
            slots: {
              default: ({ row }) => {
                const type = row.status === 0 ? 'success' : 'danger'
                return [<el-tag type={type} class="tag-item" size="mini" effect="dark" >{ this.databaseTypeOptions[row.status].dictLabel }</el-tag>]
              }
            }
          }
        ],
        buttons: [
          { type: 'export', disabled: true },
          { type: 'edit', permit:  'datax:datasource:edit', click: () => { this.handleEdit({ row: this.currentRow }) } },
          { type: 'add', click: this.handleAdd, permit: 'datax:datasource:add'},
          { type: 'search', permit: 'datax:datasource:search'},
          { type: 'import', disabled: true },
          { type: 'delete', permit: 'datax:datasource:delete', click: () => { this.handleDelete({ row: this.currentRow }) } }
        ],
        pluginTypeOptions: ['reader', 'writer'],
        pluginData: [],
        textMap: {
          update: 'edit',
          create: 'add'
        },
        showSearch: false,
        loading: false,
        currentRow: undefined,
      }
    },
    created() {
      this.getList();
      this.getDicts("sys_datasource_status").then(response => {
        this.databaseTypeOptions = response.data;
      })
    },
    watch: {
      'form.host': {
        handler: function() {
          this.selectDatabaseType(this.form.databaseType);
        }
      },
      'form.port': {
        handler: function() {
          this.selectDatabaseType(this.form.databaseType);
        }
      },
      'form.databaseName': {
        handler: function() {
          this.selectDatabaseType(this.form.databaseType);
        }
      }
    },
    methods: {
      submitForm() {
        if (this.title === '创建数据源') {
          this.form.status = 0
          this.selectDatabaseType(this.form.databaseType)
          this.$refs['form'].validate((ok) => {
            if (ok) {
              addDatasource(this.form).then(response => {
                if (response.code === 200) {
                  this.$notify({
                    type: 'success',
                    title: 'success',
                    message: '创建成功'
                  });
                  this.open = false;
                  this.getList();
                }
              });
            }
          })
        } else {
          if (this.form.jdbcPassword === this.currentRow.jdbcPassword) {
            this.form.jdbcPassword = undefined
          }
          this.$refs['form'].validate((ok) => {
            if (ok) {
              updateDatasource(this.form).then(response => {
                if (response.code === 200) {
                  this.$notify({
                    type: 'success',
                    title: 'success',
                    message: '更新成功'
                  });
                  this.open = false;
                  this.getList();
                }
              });
            }
          })
        }
      },
      /* 删除数据源 */
      handleDelete({ row }) {
        this.$XModal.confirm('确认要删除' + '"' + row.datasource + '"数据源吗?', "警告", {
          position: {
            top: 200,
            left: 'center'
          }
        })
          .then(type => {
            if (type === "confirm") {
              deleteDatasource(row.id).then(() => {
                this.$notify({
                  type: 'success',
                  title: 'success',
                  message: '删除成功'
                });
                this.getList();
              }).catch((res) => {
                this.$notify({
                  type: 'error',
                  title: '失败',
                  message: res.message
                })
              })
            }
          });
      },
      /* 编辑数据源 */
      handleEdit
        ({ row }) {
        this.title = '编辑数据源'
        row = !!row ? row : this.currentRow
        this.reset();
        this.form.id = row.id;
        this.form.databaseName = row.databaseName;
        this.form.datasource = row.datasource;
        this.form.databaseType = row.databaseType;
        this.form.host = row.host;
        this.form.port = row.port;
        this.form.jdbcDriverClass = row.jdbcDriverClass;
        this.form.jdbcUserName = row.jdbcUserName;
        this.form.jdbcPassword = row.jdbcPassword;
        this.form.jdbcUrl = row.jdbcUrl;
        this.form.comments = row.comments;
        this.form.status =row.status;
        this.selectDatabaseType(this.form.databaseType)
        this.open = true;
      },
      /* 创建数据源 */
      handleAdd() {
        this.title = '创建数据源'
        this.reset()
        this.open = true
        this.$nextTick(() => {
          this.$refs['form'].clearValidate();
        })
      },
      /* 测试数据库连接 */
      testDatasource() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            datasourceApi.test(this.temp).then(response => {
              if (response.data === false) {
                this.$notify({
                  title: 'Fail',
                  message: response.data.msg,
                  type: 'fail',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: 'Success',
                  message: 'Tested Successfully',
                  type: 'success',
                  duration: 2000
                })
              }
            })
          }
        })
      },
      selectDatabaseType(type) {
        if (type === 'mysql') {
          this.form.jdbcUrl = `jdbc:mysql://${parseStrEmpty(this.form.host,"${host}")}:${parseStrEmpty(this.form.port,"${port}")}/${parseStrEmpty(this.form.databaseName,"${database}")}`
          this.form.jdbcDriverClass = 'com.mysql.jdbc.Driver'
        } else if (type === 'oracle') {
          this.form.jdbcUrl = `jdbc:oracle:thin:@${parseStrEmpty(this.form.host,"${host}")}:${parseStrEmpty(this.form.port,"${port}")}:${parseStrEmpty(this.form.databaseName,"${sid}")}`
          this.form.jdbcDriverClass = 'oracle.jdbc.driver.OracleDriver'
        } else if (type === 'postgresql') {
          this.form.jdbcUrl = `jdbc:postgresql:/${parseStrEmpty(this.form.host,"${host}")}:${parseStrEmpty(this.form.port,"${port}")}/${parseStrEmpty(this.form.databaseName,"${database}")}`
          this.form.jdbcDriverClass = 'org.postgresql.Driver'
        } else if (type === 'sqlserver') {
          this.form.jdbcUrl = `jdbc:sqlserver://${parseStrEmpty(this.form.host,"${host}")}:${parseStrEmpty(this.form.port,"${port}")};DatabaseName=${parseStrEmpty(this.form.databaseName,"${database}")}`
          this.form.jdbcDriverClass = 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
        } else if (type === 'clickhouse') {
          this.form.jdbcUrl = 'jdbc:clickhouse://{host}:{port}/{database}'
          this.form.jdbcDriverClass = 'ru.yandex.clickhouse.ClickHouseDriver'
        } else if (type === 'hive') {
          this.form.jdbcUrl = 'jdbc:hive2://{host}:{port}/{database}'
          this.form.jdbcDriverClass = 'org.apache.hive.jdbc.HiveDriver'
        }
        // this.getShowStrategy(datasource)
      },
      reset() {
        this.form = {
          id: undefined,
          databaseType: undefined,
          datasource: undefined,
          databaseName: undefined,
          jdbcUserName: undefined,
          jdbcPassword: undefined,
          jdbcUrl: undefined,
          jdbcDriverClass: undefined,
          comments: undefined,
          host: undefined,
          port: undefined
        }
      },
      getList() {
        this.loading = true;
        listDatasource(this.queryParams).then(response => {
          this.datasourceList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      handleCurrentChange({ row }) {
        this.currentRow = row
      },
      testConnect() {
        console.log(this.form)
        testDatasource(this.form).then((res) => {
          this.$message.success(res.msg);
        }).catch(res => {
          this.$message.error(res.msg);
        })
      },
      handleQuery() {},
    }
  }
</script>

<style scoped>

</style>
